<?php
/**
 * 《银行联行号管理》实现类
 *
 * @author 孙晓晔
 * @version $Id: Country.class.php 1035 2010-03-26 05:24:59Z sunxy $
 */
require_once(dirname(__FILE__) . '/InfoUtil.class.php');

class BankCode extends InfoUtil {

	public $tbl = Constant::tbl_bank_code;
	
	public $type = array(
		'-' => '请选择',
		'1' => '普通',
		'2' => '实时',
		'9' => '其它',
	);
	
	public $bank = array(
		'-' => '请选择',			
		'招商银行' => '招商银行',
		'中信银行' => '中信银行',				
			
		'中国银行' => '中国银行',
		'中国工商银行' => '中国工商银行',
		'中国建设银行' => '中国建设银行',
		'中国农业银行' => '中国农业银行',	
		'中国民生银行' => '中国民生银行',
		'中国邮政储蓄银行' => '中国邮政储蓄银行',
		'上海浦东发展银行' => '上海浦东发展银行',
		'深圳农村商业银行' => '深圳农村商业银行',
		
		'交通银行' => '交通银行',
		'平安银行' => '平安银行',
		'华夏银行' => '华夏银行',
		
		'广发银行' => '广发银行',
		'兴业银行' => '兴业银行',
	
		'东莞银行' => '东莞银行',
		'渣打银行' => '渣打银行',
		'汇丰银行' => '汇丰银行',
	);

	public $orderby = array(
		'-' => '请选择',
		'type' => '类型',
		'bank' => '银行',
		'branch' => '分支行',
		'code' => '联行号',
		'name' => '名称',		
	
		'1' => '创建时间',
		'2' => '更新时间',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	function pretreat($controller) {
		parent::pretreat($controller);
		
		$controller->assign_by_ref('type_option', $this->type);
		$controller->assign_by_ref('bank_option', $this->bank);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);

		$controller->display($request, 'info/bank/find');
		return true;
	}
	
	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	function _where($request) {
		$code_s = $request['code_s'];
		$name_s = $request['name_s'];
		$bank_s = $request['bank_s'];
		$type_s = $request['type_s'];

		$where = " WHERE 1=1";
		
		if (!empty($code_s) && $code_s <> '-') {
			$where .= " AND code LIKE '" . $code_s . "%'";
		}

		if (!empty($name_s)) {
			$where .= " AND (name LIKE '%" . $name_s . "%' OR content LIKE '%" . $name_s . "%')";
		}
		
		if (!empty($bank_s) && $bank_s <> '-') {
			$where .= " AND bank = '" . $bank_s . "'";
		}
		
		if (!empty($type_s) && $type_s <> '-') {
			$where .= " AND type = '" . $type_s . "'";
		}

		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {

			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);
				
				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}

			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->display($request, 'info/bank/list');
		return true;
	}
	
	function import($controller, $request) {
		$this->pretreat($controller);
	
		$import = array(
			'-' => '请选择',
			'1' => '文本方式',
			'2' => '文件方式',
		);
	
		$controller->assign_by_ref('import_option', $import);
		
		$type = array(
			'-' => '请选择',
			'1' => '中信银行',
			'2' => '北京银行',
			'3' => '广发银行',
	
			'9' => '其它',
		);
		
		$controller->assign_by_ref('type_option', $type);
	
		$controller->display($request, 'info/bank/import');
		return true;
	}
	
	function importPost($controller, $request) {
		$this->pretreat($controller);
	
		$type = $request['type'];
		$oper = $request['oper'];
	
		$aa = preg_split("/[\\n]+/i", $request['data']);
		debug(print_r($aa, true));
	
		while (list($k, $v) = each($aa)) {
			$buf = trim($v);
			
			debug($buf);
	
			if ($type == '1') {
				$this->_line_1($oper, $buf);
			} else if ($type == '2') {
				$this->_line_2($oper, $buf);
			} else if ($type == '3') {
				$this->_line_3($oper, $buf);
			} 
		}
	
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));
	
		$this->findPost($controller, $request);
		return true;
	}
	
	function ajax_upload($controller, $request) {
		require_once 'HTTP/Upload.php';
		$upload = new HTTP_Upload('en');
		$file = $upload->getFiles('Filedata');
		if (PEAR::isError($file)) {
			debug($file->getMessage());
		}
	
		$oper = $request['oper'];
		$type = $request['type'];
	
		if ($file->isValid()) {
			$filename = $file->upload['tmp_name'];
			debug($filename);
	
			$this->_txt($type, $oper, $filename);
		} else {
			debug($file->getMessage());
		}
	
		echo "1";
		return true;
	}
	
	function _txt($type, $oper, $file) {
		if ($type == '1') {
			$this->_txt_1($oper, $file);
		}
	
		if ($type == '2') {
			$this->_txt_2($oper, $file);
		}
	
		if ($type == '3') {
			$this->_txt_3($oper, $file);
		}
	}
	
	function _txt_1($oper, $file) {
		$fd = fopen($file, "r");
		while (!feof($fd)) {
			$buf = $this->_to_utf8(fgets($fd));
			debug($buf);
			$this->_line_1($oper, $buf);
		}
		fclose($fd);
	}
	
	function _line_1($oper, $buf) {
		if (strlen($buf) < 5 || preg_match("/^#/i", $buf)) {
			return;
		}
	
		$a = preg_split("/(=)/", $buf);
		$no = trim($a[0]);
	
		if (!preg_match("/^(\d+)$/i", $no)) {
			return;
		}
	
		debug(print_r($a, true));
		// echo $a[1] . "\n";
	
		$code = _trim($a[0]);
		$name = _trim($a[1]);
	
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE code = '%s'";
		$sql = sprintf($fmt, $this->tbl, $code);
		debug($sql);
		$result = $db->query($sql);
		if ($db->num_rows($result) == 0) {
			$fmt = "INSERT INTO %s(code, name, oper, createtime, modifytime)";
			$fmt .= " VALUES('%s', '%s', '%s', now(), now())";
			$sql = sprintf($fmt, $this->tbl, $code, $name, $oper);
		}
		debug($sql);
		$db->query($sql);
	}
	
	function _txt_2($oper, $file) {
		$fd = fopen($file, "r");
		while (!feof($fd)) {
			$buf = $this->_to_utf8(fgets($fd));
			debug($buf);
			$this->_line_2($oper, $buf);
		}
		fclose($fd);
	}
	
	function _line_2($oper, $buf) {
		if (strlen($buf) < 5 || preg_match("/^#/i", $buf)) {
			return;
		}
	
		$a = preg_split("/,/", $buf);
		$no = trim($a[0]);
	
		if (!preg_match("/^(\d+)$/i", $no)) {
			return;
		}
	
		debug(print_r($a, true));
		// echo $a[1] . "\n";
	
		$banktype = _trim($a[0]);
		$citycode = _trim($a[1]);
		
		$name = _trim($a[2]);
		$code = _trim($a[3]);
	
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE code = '%s'";
		$sql = sprintf($fmt, $this->tbl, $code);
		debug($sql);
		$result = $db->query($sql);
		if ($db->num_rows($result) == 0) {
			$fmt = "INSERT INTO %s(banktype, citycode, name, code, oper, createtime, modifytime)";
			$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', now(), now())";
			$sql = sprintf($fmt, $this->tbl, $banktype, $citycode, $name, $code, $oper);
		} else {
			$fmt = "UPDATE %s SET banktype = '%s', citycode = '%s', modifytime = NOW() WHERE code = '%s'";
			$sql = sprintf($fmt, $this->tbl, $banktype, $citycode, $code);
		}
		debug($sql);
		$db->query($sql);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function add($controller, $request) {
		$this->pretreat($controller);

		$controller->display($request, 'info/bank/add');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function addPost($controller, $request) {
		$this->pretreat($controller);

		$type = $request['type'];
		$name = $request['name'];
		
		$bank = $request['bank'];
		$branch = $request['branch'];
		$code = $request['code'];
		
		$zjm = getPinyin($branch);
		$zjm = strtoupper($zjm);
				
		$content = addslashes($request['content']);

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(type, name, branch, code, zjm, content, status, createtime, modifytime)";
		$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $type, $name, $branch, $code, $zjm, $content, $status);
		// debug($sql);
		$db->query($sql);
		
		$request['id_s'] = $db->insert_id();

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'info/bank/edit');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$type = $request['type'];
		$name = $request['name'];
		
		$bank = $request['bank'];
		$branch = $request['branch'];
		$code = $request['code'];
		
		$zjm = getPinyin($branch);
		$zjm = strtoupper($zjm);
				
		$content = addslashes($request['content']);

		$status = $request['status'];

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET type = '%s', name = '%s', bank = '%s', branch = '%s', code = '%s', zjm = '%s'";
		$fmt .= ", content = '%s', status = '%s', modifytime = now() WHERE id = %s";
		$sql = sprintf($fmt, $this->tbl, $type, $name, $bank, $branch, $code, $zjm, $content, $status, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function view($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'info/bank/view');
		return true;
	}
	
	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}
		
		$row['type_t'] = $this->type[$row['type']];
		
		$row = $this->_view_t($row);

		return $row;
	}
	
	function _code($code) {
		$key = sprintf("%s_code_%s", $this->tbl, $code);
		
		debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			debug("getting...");
			if (is_string($ret)) {
				return $ret;
			}
		}
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE code = '%s'";
		$sql = sprintf($fmt, $this->tbl, $code);
		$result = $db->query($sql);
		
		$ret = '';
		if ($row = $db->fetch_array($result)) {
			$ret = $row['branch'];
			
			if (is_object($mc)) {
				debug("setting...");
				$mc->set($key, $ret, 0, _strtotime("1 day"));
			}
		}
	
		return $ret;
	}

	/**
	 * 测试
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function cgb($controller, $request) {

		$file = "/home/sunxy/Desktop/cgb/2.xls";
		$type = "2";
	
		require_once APP_LIB . 'excel_class.php';
		Read_Excel_File($file, $return);
		
		while (list($k, $buf) = each($return)) {

			$this->_xls($buf, $type);
		}

		$controller->display($request, 't');
		return true;
	}
		
	function _xls($buf, $type) {
		$db = newdb($this->dsn_w);
		for($j = 1; $j < count($buf); $j++) {
			$a = $buf[$j];

			print_r($a);

			$fmt = "INSERT INTO %s(type, code, name, createtime, modifytime)";
			$fmt .= " VALUES('%s', '%s', '%s', NOW(), NOW())";
			$sql = sprintf($fmt, $this->tbl, $type, $a[0], $a[1]);
			// echo $sql . "\n";
			$db->query($sql);
		}
	}
	
	function ajax_zjm($controller, $request) {
		$this->pretreat($controller);
		
		$data = $this->_ajax_zjm($request);
		echo json_encode($data);
	}

	function _ajax_zjm($request) {
		debug(print_r($request, true));
		
		$bank = $request['bank'];		
		$q = $request['q'];
		$n = $request['maxRows'];
		if (empty($n)) {
			$n = 20;
		}
		
		$key = sprintf("%s_%s_%s_%s_%s", $this->tbl, $this->zjm, $this->prefix, substr(md5($bank), 0, 8), $q);
		debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (is_array($ret)) {
				return $ret;
			}
		}

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE bank = '%s' AND zjm LIKE '%s'";
		$sql = sprintf($fmt, $this->tbl, $bank, "%" . $q . "%");
		debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {

			$ret[] = $row;
		}
		
		if (is_object($mc) && count($ret) > 0) {
			$mc->set($key, $ret, 0, _strtotime("3 day"));
		}

		return $ret;
	}

	function z($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s";
		$fmt = "SELECT * FROM %s WHERE zjm is NULL";
		$fmt = "SELECT * FROM %s WHERE createtime > '2014-09-01'";
		$sql = sprintf($fmt, $this->tbl);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$zjm = getPinyin($row['branch']);
			$zjm = strtoupper($zjm);

			$fmt = "UPDATE %s SET zjm = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $zjm, $row['id']);
			echo ".";
			$db->query($sql);
		}

		logdate($controller, $request);
		return true;
	}
	
	function ccc($controller, $request) {
		$this->pretreat($controller);
	
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET bank = REPLACE(bank, '有限责任银行', '有限责任公司') WHERE createtime > '2014-09-01'";
		// $fmt = "SELECT * FROM %s where id = 131550";
		$sql = sprintf($fmt, $this->tbl);
		$db->query($sql);
		
		logdate($controller, $request);
		return true;
	}
	
	function b($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s where createtime > '2014-09-01'";
		// $fmt = "SELECT * FROM %s where id = 131550";
		$sql = sprintf($fmt, $this->tbl);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$bank = $this->_bank($row['name']);
			$branch = $this->_branch($row['name']);
			$zjm = getPinyin($branch);
			$zjm = strtoupper($zjm);

			$fmt = "UPDATE %s SET bank = '%s', branch = '%s', zjm = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $bank, $branch, $zjm, $row['id']);
			// debug($sql);
			echo $sql . "\n";
			$db->query($sql);
		}

		logdate($controller, $request);
		return true;
	}
	
	function _bank($s) {
		$a = preg_split("/银行|公司/", $s);
		print_r($a);
		
		return $a[0] . "银行";
	}
	
	function _branch($s) {
		$a = preg_split("/银行|公司|合作联社/", $s);
		if (count($a) > 2) {
			return $a[2];
		} else if (count($a) > 1) {
		
			return $a[1];
		} 
		
		return $a[0];
	}
	
	function bj($controller, $request) {
		$filename = '/Users/sunxiaoye/Documents/bank.txt';
		
		$this->_txt('2', '101', $filename);

		logdate($controller, $request);
		return true;
	}
	
	function citic($controller, $request) {
		$file = '/Users/sunxiaoye/Downloads/zx_lhh.txt';
		$oper = '101';
	
		$fd = fopen($file, "r");
		while (!feof($fd)) {
			// $buf = $this->_to_utf8(fgets($fd));
			$buf = fgets($fd);
			// echo $buf . "\n";
			$this->_citic_line($oper, $buf);
		}
		fclose($fd);
	
		logdate($controller, $request);
		return true;
	}
	
	function _citic_line($oper, $buf) {
		if (strlen($buf) < 5 || preg_match("/^#/i", $buf)) {
			return;
		}
	
		$a = preg_split("/=/", $buf);
		
		$name = trim($a[1]);
		$code = trim($a[0]);
		
		$banktype = substr($code, 0, 3);
		$citycode = substr($code, 3, 4);
	
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE code = '%s'";
		$sql = sprintf($fmt, $this->tbl, $code);
		// echo $sql . "\n";
		$result = $db->query($sql);
		if ($db->num_rows($result) == 0) {
			$fmt = "INSERT INTO %s(banktype, citycode, name, code, oper, createtime, modifytime)";
			$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', now(), now())";
			$sql = sprintf($fmt, $this->tbl, $banktype, $citycode, $name, $code, $oper);
			echo $sql . "\n";
			$db->query($sql);
		} else {
			$fmt = "UPDATE %s SET banktype = '%s', citycode = '%s', modifytime = NOW() WHERE code = '%s'";
			$sql = sprintf($fmt, $this->tbl, $banktype, $citycode, $code);
			echo ".";
			// echo $sql . "\n";
			// $db->query($sql);
		}
	}
}

function _trim($s) {
	$s = trim($s);
	if (empty($s)) {
		return '';
	}

	$s = preg_replace("/[\s|\"|\'|,|-]+/i", "", $s);

	return $s;
}
?>